const express = require('express')
const router = express.Router()
const humps = require('humps')
const db = require('../../database/db')

module.exports = (() => {
    // 中心部门业务员管理
    router.get('/centers', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getCenters())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.get('/departments', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getDepartments())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.get('/salesmans', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getSalesmans({ limit: req.query.limit, offset: req.query.offset, search: req.query.search }))
            const { total } = await db.getSalesmansTotal(req.query.search)
            res.send({
                doc,
                total
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/departmentList', async (req, res, next) => {
        try {
            const { id } = await db.getCenterByName(req.body.center)
            const data = await db.getDeptByCenterId(id)
            res.send(data)
        } catch (err) {
            next(err)
        }
    })

    router.post('/salesmanList', async (req, res, next) => {
        try {
            const center = await db.getCenterByName(req.body.center)
            const dept = await db.getDeptByName({ name: req.body.dept, center: req.body.center })
            const data = await db.getSalesman({ center_id: center.id, dept_id: dept.id })
            res.send(data)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addCenter', async (req, res, next) => {
        try {
            let existCenter = await db.getCenterByName(req.body.name)
            if (existCenter) {
                res.json({
                    status: 0,
                    msg: '该中心已存在！'
                })
                return
            }

            db.addCenter(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/addDepartment', async (req, res, next) => {
        try {
            let existDept = await db.getDeptByName({ name: req.body.name, center: req.body.center })
            if (existDept) {
                res.json({
                    status: 0,
                    msg: '该部门已存在！'
                })
                return
            }

            const { id } = await db.getCenterByName(req.body.center) // 获取中心表数据
            const success = await db.addDept({ name: req.body.name, center_id: id }) // 添加部门表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.post('/addSalesman', async (req, res, next) => {
        try {
            // 判断业务员是否存在
            let existSalesman = await db.getSalesmanByName({ name: req.body.name, dept: req.body.dept, center: req.body.center })
            if (existSalesman) {
                res.json({
                    status: 0,
                    msg: '该业务员已存在！'
                })
                return
            }

            const center = await db.getCenterByName(req.body.center)
            const dept = await db.getDept({ center_id: center.id, name: req.body.dept })
            const success = await db.addSalesman({ name: req.body.name, center_id: center.id, dept_id: dept.id })
            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.post('/salesmanSearch', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getSalesmanBySearch(req.body.search))
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.put('/editCenter/:id', async (req, res, next) => {
        try {
            let existCenter = await db.getCenterById(req.params.id)
            if (!existCenter) {
                res.json({
                    status: 0,
                    msg: '该中心不存在！'
                })
                return
            }

            db.updateCenter(req.params.id, req.body).then(() => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editDepartment/:id', async (req, res, next) => {
        try {
            let existDept = await db.getDeptById(req.params.id)
            let existRepeat = await db.getDeptByName({ name: req.body.name, center: req.body.center })
            if (!existDept) {
                res.json({
                    status: 0,
                    msg: '该部门不存在！'
                })
                return
            }

            if (existRepeat) {
                res.json({
                    status: 0,
                    msg: '该部门已存在！'
                })
                return
            }

            const { id } = await db.getCenterByName(req.body.center); // 获取中心表数据
            await db.updateDept({ name: req.body.name, id: req.params.id, center_id: id }) // 更新部门表数据
            await db.updateRelationD({ id: req.params.id, center_id: id })
            const success = await db.updateSalesmanAll({ dept_id: req.params.id, center_id: id }) // 更新部门下的销售员表

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.put('/editSalesman/:id', async (req, res, next) => {
        try {
            let existSalesman = await db.getSalesmanById(req.params.id)
            if (!existSalesman) {
                res.json({
                    status: 0,
                    msg: '该业务员不存在！'
                })
                return
            }
            let existRepeat = await db.getSalesmanByName({ name: req.body.name, dept: req.body.dept, center: req.body.center })
            if (existRepeat) {
                res.json({
                    status: 0,
                    msg: '该业务员已存在！'
                })
                return
            }
            
            const center = await db.getCenterByName(req.body.center); // 获取中心表数据
            const dept = await db.getDeptByName({ name: req.body.dept, center: req.body.center }); // 获取部门表数据
            await db.updateRelationS({ id: req.params.id, center_id: center.id, dept_id: dept.id })
            const success = await db.updateSalesman({ id: req.params.id, name: req.body.name, dept_id: dept.id, center_id: center.id }) // 更新部门表数据
            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeCenter/:id', async (req, res, next) => {
        try {
            let existCenter = await db.getCenterById(req.params.id)
            if (!existCenter) {
                res.json({
                    status: 0,
                    msg: '该中心不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'center_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }
            await db.rmCenterById(req.params.id) // 删除中心表数据
            await db.rmDeptByCenterId(req.params.id) // 删除中心下的部门表数据
            const success = await db.rmSalesmanByCenterId(req.params.id) // 删除中心表下的部门下的业务员表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeDepartment/:id', async (req, res, next) => {
        try {
            let existDept = await db.getDeptById(req.params.id)
            if (!existDept) {
                res.json({
                    status: 0,
                    msg: '该部门不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'department_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }
            await db.rmDeptById(req.params.id) // 删除部门表数据
            const success = await db.rmSalesmanByDeptId(req.params.id) // 删除部门下的业务员表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeSalesman/:id', async (req, res, next) => {
        try {
            let existSalesman = await db.getSalesmanById(req.params.id)
            if (!existSalesman) {
                res.json({
                    status: 0,
                    msg: '该业务员不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'salesman_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }
            const success = await db.rmSalesmanById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })
    // 市场管理
    router.get('/trials', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getTrials())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addTrial', async (req, res, next) => {
        try {
            let existTrial = await db.getTrialByName(req.body.name)
            if (existTrial) {
                res.json({
                    status: 0,
                    msg: '该渠道已存在！'
                })
                return
            }

            db.addTrial(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editTrial/:id', async (req, res, next) => {
        try {
            let existTrial = await db.getTrialById(req.params.id)
            if (!existTrial) {
                res.json({
                    status: 0,
                    msg: '该渠道不存在！'
                })
                return
            }

            const success = await db.updateTrial({ id: req.params.id, name: req.body.name })

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeTrial/:id', async (req, res, next) => {
        try {
            let existTrial = await db.getTrialById(req.params.id)
            if (!existTrial) {
                res.json({
                    status: 0,
                    msg: '该渠道不存在！'
                })
                return
            }

            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'trial_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }
            const success = await db.rmTrialById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/cancellations', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getCancellations())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addCancellation', async (req, res, next) => {
        try {
            let existCancellation = await db.getCancellationByName(req.body.name)
            if (existCancellation) {
                res.json({
                    status: 0,
                    msg: '该条已存在！'
                })
                return
            }

            db.addCancellation(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editCancellation/:id', async (req, res, next) => {
        try {
            let existCancellation = await db.getCancellationById(req.params.id)
            if (!existCancellation) {
                res.json({
                    status: 0,
                    msg: '该条退单原因不存在！'
                })
                return
            }

            const success = await db.updateCancellation({ id: req.params.id, name: req.body.name })

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeCancellation/:id', async (req, res, next) => {
        try {
            let existCancellation = await db.getCancellationById(req.params.id)
            if (!existCancellation) {
                res.json({
                    status: 0,
                    msg: '该条退单原因不存在！'
                })
                return
            }

            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'cancellation_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }

            const success = await db.rmCancellationById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/promotions', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getPromotions())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addPromotion', async (req, res, next) => {
        try {
            let existPromotion = await db.getPromotionByName(req.body.name)
            if (existPromotion) {
                res.json({
                    status: 0,
                    msg: '该条已存在！'
                })
                return
            }

            db.addPromotion(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editPromotion/:id', async (req, res, next) => {
        try {
            let existPromotion = await db.getPromotionById(req.params.id)
            if (!existPromotion) {
                res.json({
                    status: 0,
                    msg: '该条推广渠道不存在！'
                })
                return
            }

            const success = await db.updatePromotion({ id: req.params.id, name: req.body.name })

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removePromotion/:id', async (req, res, next) => {
        try {
            let existPromotion = await db.getPromotionById(req.params.id)
            if (!existPromotion) {
                res.json({
                    status: 0,
                    msg: '该条推广渠道不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'promotion_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }
            const success = await db.rmPromotionById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/notsignings', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getNotSigns())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addNotsigning', async (req, res, next) => {
        try {
            let existNotSign = await db.getNotSignByName(req.body.name)
            if (existNotSign) {
                res.json({
                    status: 0,
                    msg: '该条已存在！'
                })
                return
            }

            db.addNotSign(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editNotsigning/:id', async (req, res, next) => {
        try {
            let existNotSign = await db.getNotSignById(req.params.id)
            if (!existNotSign) {
                res.json({
                    status: 0,
                    msg: '该条未不存在！'
                })
                return
            }

            const success = await db.updateNotSign({ id: req.params.id, name: req.body.name })

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeNotsigning/:id', async (req, res, next) => {
        try {
            let existNotSign = await db.getNotSignById(req.params.id)
            if (!existNotSign) {
                res.json({
                    status: 0,
                    msg: '该条未不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'notsigning_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }
            const success = await db.rmNotSignById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/notpasss', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getNotpasss())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addNotpass', async (req, res, next) => {
        try {
            let existNotpass = await db.getNotpassByName(req.body.name)
            if (existNotpass) {
                res.json({
                    status: 0,
                    msg: '该条已存在！'
                })
                return
            }

            db.addNotpass(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editNotpass/:id', async (req, res, next) => {
        try {
            let existNotpass = await db.getNotpassById(req.params.id)
            if (!existNotpass) {
                res.json({
                    status: 0,
                    msg: '该条不存在！'
                })
                return
            }

            const success = await db.updateNotpass({ id: req.params.id, name: req.body.name })

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeNotpass/:id', async (req, res, next) => {
        try {
            let existNotpass = await db.getNotpassById(req.params.id)
            if (!existNotpass) {
                res.json({
                    status: 0,
                    msg: '该条不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'notpass_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }
            const success = await db.rmNotpassById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/distributions', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getDistributions())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addDistribution', async (req, res, next) => {
        try {
            let existDistribution = await db.getDistributionByName(req.body.name)
            if (existDistribution) {
                res.json({
                    status: 0,
                    msg: '该条已存在！'
                })
                return
            }

            db.addDistribution(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editDistribution/:id', async (req, res, next) => {
        try {
            let existDistribution = await db.getDistributionById(req.params.id)
            if (!existDistribution) {
                res.json({
                    status: 0,
                    msg: '该条不存在！'
                })
                return
            }

            const success = await db.updateDistribution({ id: req.params.id, name: req.body.name })

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeDistribution/:id', async (req, res, next) => {
        try {
            let existDistribution = await db.getDistributionById(req.params.id)
            if (!existDistribution) {
                res.json({
                    status: 0,
                    msg: '该条不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'distribution_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }

            const success = await db.rmDistributionById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/warrantMans', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getWarrantMans())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addWarrantMan', async (req, res, next) => {
        try {
            let existWarrantMan = await db.getWarrantManByName(req.body.name)
            if (existWarrantMan) {
                res.json({
                    status: 0,
                    msg: '该专员已存在！'
                })
                return
            }

            db.addWarrantMan(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editWarrantMan/:id', async (req, res, next) => {
        try {
            let existWarrantMan = await db.getWarrantManById(req.params.id)
            if (!existWarrantMan) {
                res.json({
                    status: 0,
                    msg: '该专员不存在！'
                })
                return
            }

            const success = await db.updateWarrantMan({ id: req.params.id, name: req.body.name })

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeWarrantMan/:id', async (req, res, next) => {
        try {
            let existWarrantMan = await db.getWarrantManById(req.params.id)
            if (!existWarrantMan) {
                res.json({
                    status: 0,
                    msg: '该条不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'warrant_man_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }

            const success = await db.rmWarrantManById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.get('/negotiators', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getNegotiators())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/addNegotiator', async (req, res, next) => {
        try {
            let existNegotiator = await db.getNegotiatorByName(req.body.name)
            if (existNegotiator) {
                res.json({
                    status: 0,
                    msg: '该谈判师已存在！'
                })
                return
            }

            db.addNegotiator(req.body).then(async (data) => {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editNegotiator/:id', async (req, res, next) => {
        try {
            let existNegotiator = await db.getNegotiatorById(req.params.id)
            if (!existNegotiator) {
                res.json({
                    status: 0,
                    msg: '该谈判师不存在！'
                })
                return
            }

            const success = await db.updateNegotiator({ id: req.params.id, name: req.body.name })

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeNegotiator/:id', async (req, res, next) => {
        try {
            let existNegotiator = await db.getNegotiatorById(req.params.id)
            if (!existNegotiator) {
                res.json({
                    status: 0,
                    msg: '该条不存在！'
                })
                return
            }
            let existRelation = await db.getRecordByRelationId({ id: req.params.id, type: 'negotiator_id' })
            if (existRelation.length) {
                res.json({
                    status: 0,
                    msg: '请先修改或删除关联数据！'
                })
                return
            }

            const success = await db.rmNegotiatorById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    return router
})();